package com.common.util;

import java.util.Date;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;


/**
* @version: V1.0
* @author: szw
* @className: JWTUtils
* @packageName: JWTUtils
* @description: JWT 工具类
* @data: 2021-1-19 
**/  
@Slf4j
public class JWTUtils {

    private final static String key ="ysjwt" ;
    private final static long ttl= 3600000 ;//一个小时


    /**
     * 生成JWT
     *
     * @param id
     * @param subject
     * @return
     */
    public static String  createJWT(Long id, String subject, String roleCd) {
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        JwtBuilder builder = Jwts.builder().setId(String.valueOf(id))
                .setSubject(subject)
                .setIssuedAt(now)
                .signWith(SignatureAlgorithm.HS256, key).claim("roleCd", roleCd);
        if (ttl > 0) {
            builder.setExpiration( new Date( nowMillis + ttl));
        }
        return builder.compact();
    }

    /**
     * 解析JWT
     * @param jwtStr
     * @return
     */
    public static Claims parseJWT(String jwtStr){
        return  Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(jwtStr)
                .getBody();
    }
}
